package com.example.im.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.im.R
import com.example.im.bean.UserRoom
import com.xlkj.ehobe.storage.ui.adapter.holder.RecyclerViewHolder
import kotlinx.android.synthetic.main.recycler_item_friend_new.view.*


class FriendRequestAdapter(
    private val mContext: Context,
    private val users: MutableList<UserRoom>
) :
    RecyclerView.Adapter<RecyclerViewHolder>() {


    private var mOnClickItemListener: OnClickItemListener? = null

    fun setOnItemClickListener(mOnClickItemListener: OnClickItemListener) {
        this.mOnClickItemListener = mOnClickItemListener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        return RecyclerViewHolder(
            LayoutInflater.from(mContext).inflate(R.layout.recycler_item_friend_new, parent, false)
        )
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {

        val view: View = holder.itemView
        view.tv_user_name.text = users[position].nickname
        view.tv_new_agree.setOnClickListener { v ->
            mOnClickItemListener!!.onClickItem(v, position)
        }
        view.tv_new_refuse.setOnClickListener { v ->
            mOnClickItemListener!!.onClickItem(v, position)
        }
        view.tag = position
    }

    override fun getItemCount(): Int {
        return users.size
    }

    /**
     * 添加所有数据
     * */
    fun addDataAll(users: MutableList<UserRoom>) {
        this.users.clear()
        this.users.addAll(users)
        this.notifyDataSetChanged()
    }

    /**
     * 添加条目
     * */
    fun addDataItem(user: UserRoom) {
        if (users.none { it.id == user.id }) {
            this.users.add(itemCount, user)
            this.notifyItemChanged(itemCount)
        } else for ((index, value) in this.users.withIndex())
            if (value.id == user.id) {
                this.users[index] = user
                this.notifyItemChanged(index)
                return
            }
    }

    /**
     * 移除条目
     * */
    fun removeDataItem(user: UserRoom) {
        for ((index, value) in this.users.withIndex()) if (value.id == user.id) {
            this.users.removeAt(index)
            this.notifyItemRangeRemoved(index, itemCount + 1)
            return
        }
    }

    /**
     * 更新条目
     * */
    fun upDataItem(user: UserRoom) {
        for ((index, value) in this.users.withIndex()) if (value.id == user.id) {
            this.users[index] = user
            this.notifyItemChanged(index)
            return
        }
    }

    interface OnClickItemListener {
        fun onClickItem(view: View, position: Int)
    }
}
